package com.zzyl.service.impl;

import cn.hutool.core.bean.BeanUtil;
import cn.hutool.core.util.StrUtil;
import com.alibaba.fastjson.JSON;
import com.github.pagehelper.Page;
import com.github.pagehelper.PageHelper;
import com.zzyl.base.PageResponse;
import com.zzyl.constant.SuperConstant;
import com.zzyl.dto.RoleDto;
import com.zzyl.entity.Role;
import com.zzyl.entity.RoleResource;
import com.zzyl.entity.UserRole;
import com.zzyl.mapper.RoleMapper;
import com.zzyl.mapper.RoleResourceMapper;
import com.zzyl.mapper.UserRoleMapper;
import com.zzyl.service.RoleService;
import com.zzyl.utils.EmptyUtil;
import com.zzyl.vo.RoleVo;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
import java.util.Set;

/**
 * @Description RoleServiceImpl
 * @Author chenchuang
 * @Date 2024-09-01
 */
@Service
public class RoleServiceImpl implements RoleService {

    @Autowired
    private RoleMapper roleMapper;

    @Autowired
    private UserRoleMapper userRoleMapper;

    @Autowired
    private RoleResourceMapper roleResourceMapper;
    @Qualifier("redisTemplate")
    @Autowired
    private RedisTemplate redisTemplate;

    @Override
    public PageResponse<RoleVo> getByPage(RoleDto roleDto, Integer pageNum, Integer pageSize) {
        String key = "roleCache"+pageNum+"_"+pageSize+"_"+roleDto.hashCode();
        String json = (String) redisTemplate.opsForValue().get(key);
        PageResponse<RoleVo> pageResponse = null;
        if(StrUtil.isEmpty(json)){
            PageHelper.startPage(pageNum, pageSize);
            Page<Role> page = roleMapper.selectPage(roleDto);
            pageResponse = PageResponse.of(page, RoleVo.class);
            redisTemplate.opsForValue().set(key, JSON.toJSONString(pageResponse));
        }else {
            pageResponse = JSON.parseObject(json, PageResponse.class);
        }
        return pageResponse;
    }

    private void clearCache(String key) {
        Set<String> keys = redisTemplate.keys(key);
        redisTemplate.delete(keys);
    }

    @Transactional
    @Override
    public void createRole(RoleDto roleDto) {
        Role role = BeanUtil.copyProperties(roleDto, Role.class);
        roleMapper.insert(role);
        clearCache("roleCache*");
    }

    @Override
    public Set<String> findCheckedResources(Long roleId) {
        return roleResourceMapper.selectResourceNoByRoleId(roleId);
    }

    @Override
    public Boolean updateRole(RoleDto roleDto) {
        //1.类型转换
        Role role = BeanUtil.toBean(roleDto, Role.class);
        //TODO 角色是否关联用户，如果关联，则不能禁用
        List<UserRole> userRoleList =  userRoleMapper.selectByRoleId(roleDto.getId());
        if (!EmptyUtil.isNullOrEmpty(userRoleList)&&roleDto.getDataState()!=null) {
            throw new RuntimeException("角色关联用户，不能禁用");
        }
        //2.调用修改角色的mapper
        roleMapper.updateByPrimaryKeySelective(role);
        clearCache("roleCache*");
        //3.判断是否修改角色对应的资源数据
        if (roleDto.getCheckedResourceNos() == null) {
            return true;
        }
        roleResourceMapper.deleteRoleResourceByRoleId(role.getId());
        List<RoleResource> roleResourceList = getRoleResourceList(roleDto, role);
        if (roleResourceList.isEmpty()) {
            return true;
        }
        roleResourceMapper.batchInsert(roleResourceList);

        return true;
    }

    @Override
    public int deleteRoleById(Long roleId) {
        roleResourceMapper.deleteRoleResourceByRoleId(roleId);
        clearCache("roleCache*");
        return roleMapper.deleteByPrimaryKey(roleId);
    }

    @Override
    public Set<String> initRoles() {
        return roleMapper.select();
    }



    private static List<RoleResource> getRoleResourceList(RoleDto roleDto, Role role) {
        List<RoleResource> roleResourceList = new ArrayList<>();
        //4.2.3 遍历封装数据
        String[] checkedResourceNos = roleDto.getCheckedResourceNos();
        List<String> resourceNoList = Arrays.asList(checkedResourceNos);
        resourceNoList.forEach(resourceNo ->{
            RoleResource roleResource = RoleResource.builder()
                    .roleId(role.getId())
                    .resourceNo(resourceNo)
                    .dataState(SuperConstant.DATA_STATE_0)
                    .build();
            roleResourceList.add(roleResource);
        });
        return roleResourceList;
    }
}
